package org.stvd.service.admin.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.stvd.common.SecurityUserHolder;
import org.stvd.common.enums.AuthRoleEnum;
import org.stvd.common.utils.ServiceResult;
import org.stvd.common.utils.ServiceUtils;
import org.stvd.core.util.DateUtil;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Department;
import org.stvd.entities.admin.Guids;
import org.stvd.entities.admin.Resources;
import org.stvd.entities.admin.Roles;
import org.stvd.repository.admin.DepartmentDao;
import org.stvd.repository.admin.GuidsDao;
import org.stvd.repository.admin.ResourcesDao;
import org.stvd.repository.admin.RoleResDao;
import org.stvd.repository.admin.RolesDao;
import org.stvd.repository.admin.UserDepDao;
import org.stvd.repository.admin.UserGuidDao;
import org.stvd.repository.admin.UserRoleDao;
import org.stvd.service.admin.GuidsService;
import org.stvd.service.base.impl.BaseServiceImpl;

@Service("guidsService")
public class GuidsServiceImpl extends BaseServiceImpl<Guids> implements GuidsService {

    @Resource(name="GuidsDao")
    private GuidsDao guidsDao;
    @Resource(name="DepartmentDao")
    private DepartmentDao departmentDao;
    @Resource(name="RolesDao")
    private RolesDao rolesDao;
    @Resource(name ="ResourcesDao")
    private ResourcesDao resourcesDao;
    @Resource(name = "UserDepDao")
    private UserDepDao userDepDao;
    @Resource(name = "UserRoleDao")
    private UserRoleDao userRoleDao;
    @Resource(name = "UserGuidDao")
    private UserGuidDao userGuidDao;
    @Resource(name = "RoleResDao")
    private RoleResDao roleResDao;

    public List<Guids> listAllGuids(String innerCode, String status) {
        return guidsDao.listAllGuids(innerCode, status);
    }
    
    @Override
    public List<Guids> listAllChildGuids(String guid) {
        return guidsDao.listAllChildGuids(guid);
    }
    
    @Override
    public List<Guids> listGuidsByUpperGuid(String guid) {
        return guidsDao.listGuidsByUpperGuid(guid);
    }
    
    @Override
    public List<Guids> listGuidByUserId(String userId) {
        return guidsDao.listGuidByUserId(userId);
    }
    
    @Override
    public boolean isChildGuids(String guid, String upperGuid) {
        boolean bResult = false;
        List<Guids> list = guidsDao.listAllChildGuids(guid);
        for (Guids guids : list) {
            if (guids.getGuid().equals(upperGuid)) {
                bResult = true;
            }
        }
        return bResult;
    }
    
    @Override
    public String getInnerCode(String upperGuid) {
        String innerCode = "";
        if("-1".equals(upperGuid)) {
            innerCode = ServiceUtils.getInnerCode("G");
        }else {
            Guids guids = guidsDao.findByPk(Guids.class, upperGuid);
            if(guids!=null) {
                innerCode = ServiceUtils.getInnerCode(guids.getInnerCode());
            }
        }
        return innerCode;
    }
    
    @Override
    public String getPlatformCode(String guid) {
        String platformCode = "";
        if(!StringUtil.isEmpty(guid)) {
            Guids guids = guidsDao.findByPk(Guids.class, guid);
            if(guids!=null) {
                platformCode = guids.getSysModuleCode();
            }
        }
        return platformCode;
    }
    
    @Override
    @Transactional
    public ServiceResult<Map<String, Object>> insertGuidsAndInit(Guids guids) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<Map<String,Object>>();
        String userId = SecurityUserHolder.getCurrentUserid();
        String guid = guids.getGuid();
        if(guidsDao.findByPk(Guids.class, guid)!=null) {
            serviceResult.setParamError("当前GUID‘"+guid+"’已经存在！");
            return serviceResult;
        }
        guids.setInnerCode(getInnerCode(guids.getUpperGuid()));
        guids.setStatus("T");
        guids.setIndate(DateUtil.getSystemDate());
        guidsDao.insert(guids);
        if(!"-1".equals(guids.getSysModuleType())) {
            // 初始化机构信息[数据中心]
            String depId = StringUtil.getRandomUUID();
            Department department = new Department();
            department.setDepId(depId);
            department.setDepType("1");
            department.setUpperId("-1");
            department.setDepName("数据中心");
            department.setDepCode("999999");
            department.setInnerCode(StringUtil.formatStrLen(department.getDepCode(), 10));
            department.setJsm("SJZX");
            department.setAreaNo("000000");
            department.setInputDate(DateUtil.getSystemDate());
            department.setOperator(userId);
            department.setState("T");
            department.setGuid(guid);
            departmentDao.insert(department);
            
            // 初始化资源信息[前台通用、后台通用]
            String resId_WEB = StringUtil.getRandomUUID();
            Resources resources = new Resources();
            resources.setResId(resId_WEB);
            resources.setType("URL");
            resources.setName("前台WEB请求");
            resources.setContent("/web/**");
            resources.setPriority(1);
            resources.setMemo("前台WEB请求");
            resources.setGuid(guid);
            resourcesDao.insert(resources);
            
            String resId_ADMIN = StringUtil.getRandomUUID();
            resources = new Resources();
            resources.setResId(resId_ADMIN);
            resources.setType("URL");
            resources.setName("后台业务管理请求");
            resources.setContent("/**");
            resources.setPriority(99);
            resources.setMemo("后台业务管理请求");
            resources.setGuid(guid);
            resourcesDao.insert(resources);
            
            // 初始化角色信息[认证：个人、专家、团队、企业]
            for (AuthRoleEnum roleStr : AuthRoleEnum.values()) {
                Roles roles = new Roles();
                roles.setRoleId(StringUtil.getRandomUUID());
                roles.setRoleName(roleStr.getText());
                roles.setRoleCode(roleStr.getValue());
                roles.setMemo(roleStr.getText());
                roles.setEnable("T");
                roles.setDepId(depId);
                roles.setGuid(guid);
                roles.setBuildIn("0");
                rolesDao.insert(roles);
            }
            String roleId_ANONYMOUS = StringUtil.getRandomUUID();
            Roles roles = new Roles();
            roles.setRoleId(roleId_ANONYMOUS);
            roles.setRoleName("匿名");
            roles.setRoleCode("ROLE_ANONYMOUS");
            roles.setMemo("匿名");
            roles.setEnable("T");
            roles.setDepId(depId);
            roles.setGuid(guid);
            roles.setBuildIn("0");
            rolesDao.insert(roles);
            
            String roleId_REGISTER = StringUtil.getRandomUUID();
            roles = new Roles();
            roles.setRoleId(roleId_REGISTER);
            roles.setRoleName("注册用户");
            roles.setRoleCode("ROLE_REGISTER");
            roles.setMemo("平台默认基础角色，可认证其他角色");
            roles.setEnable("T");
            roles.setDepId(depId);
            roles.setGuid(guid);
            roles.setBuildIn("0");
            rolesDao.insert(roles);
            
            String roleId_ADMIN = StringUtil.getRandomUUID();
            roles = new Roles();
            roles.setRoleId(roleId_ADMIN);
            roles.setRoleName("系统管理员");
            roles.setRoleCode("ROLE_ADMIN");
            roles.setMemo("拥用本平台最高权限，可对下属机构用户分配权限！");
            roles.setEnable("T");
            roles.setDepId(depId);
            roles.setGuid(guid);
            roles.setBuildIn("0");
            rolesDao.insert(roles);
            
            // 初始化用户角色、机构、资源映射信息
            userGuidDao.insert(userId, guid);
            userDepDao.insert(userId, new String[]{depId}, guid);
            userRoleDao.insert(userId, new String[]{roleId_REGISTER, roleId_ADMIN}, guid);
            roleResDao.insertRoleRes(roleId_ANONYMOUS, new String[]{resId_WEB}, guid);
            roleResDao.insertRoleRes(roleId_ADMIN, new String[]{resId_WEB, resId_ADMIN}, guid);
        }    
        serviceResult.setMessage("新增成功！");
        return serviceResult;
    }
}
